#include "mgmt_bk.h"
#include <stdlib.h>
#include <string.h>

status mgmt_bk_init(mgmt_bk_sqlist *l){
    book* b=(book*)malloc(sizeof(book)*(maxsize+1));
    if(!b) exit(overflow);
    l->elem=b;
    l->length=0;
    return ok;
}

status mgmt_bk_insert(mgmt_bk_sqlist *l,book b){
    if(l->length>=maxsize) return error;
    l->elem[l->length+1]=b;
    l->length++;
    return ok;
}

status mgmt_bk_delete_name(mgmt_bk_sqlist *l,char *name){

}

status mgmt_bk_delete_id(mgmt_bk_sqlist *l,int *id){

}

status mgmt_bk_edit(mgmt_bk_sqlist *l,int *id,book bk_new){

}

status mgmt_bk_find(mgmt_bk_sqlist *l,char *bid,book **res){
    for(int i=1;i<=l->length;i++){
        if(strcmp(l->elem[i].id,bid)==0){
            *res=&l->elem[i];
            return ok;
        }
    }
    return error;
}

int cmp_by_null(book a,book b){
    return 0;
}

int cmp_by_name(book a,book b){

}
int cmp_by_price(book a,book b){
    return a.price - b.price;
}
void swap(book *arr,int i,int j){
    book tmp=arr[i];
    arr[i]=arr[j];
    arr[j]=tmp;
}
void print_book(book b){
    char *id=b.id;
    while((*id)!='\0')printf("%c",*id++);
    printf("          ");
    char *name=b.name;
    while((*name)!='\0')printf("%c",*name++);
    printf("          ");
    printf("%d\n",b.price);
}
status mgmt_bk_traverse(mgmt_bk_sqlist *l,func_cmp op){
    printf("-----------id--------------name--------------price\n");
    if(op==cmp_by_null){
        for(int i=1;i<=l->length;i++){
           print_book(l->elem[i]);
        }
        return ok;
    }
    book* tmp=(book*)malloc(sizeof(book)*(l->length+1));
    if(!tmp) exit(overflow);
    for(int i=1;i<=l->length;i++){
        tmp[i]=l->elem[i];
    }
    for(int i=1;i<l->length;i++){
        for(int j=1;j<=l->length-i;j++){
            if(op(tmp[j],tmp[j+1])>0){
                swap(tmp,j,j+1);
            }
        }
    }
    for(int k=1;k<=l->length;k++){
        print_book(tmp[k]);
    }
    free(tmp);
    return ok;
}